package ru.yermak.bookkeeping.ui;

import ru.yermak.bookkeeping.common.DataModel;
import ru.yermak.bookkeeping.model.Selectable;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;

/**
 * User: harrier
 * Date: Nov 5, 2008
 */
public class TableSelector implements Selector {
    private String name;
    private JTable table;
    private DataModel dataModel;
    private Integer selectedId;


    public TableSelector(String name, JTable table, DataModel dataModel) {
        this.name = name;
        this.table = table;
        this.dataModel = dataModel;
        this.table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        this.table.getSelectionModel().setValueIsAdjusting(false);
        this.table.getSelectionModel().addListSelectionListener(this);
    }


    public void valueChanged(ListSelectionEvent e) {
        ListSelectionModel source = (ListSelectionModel) e.getSource();
        int selectionIndex = source.getMinSelectionIndex();
        if (selectionIndex == -1) return;
        Selectable selected = (Selectable) dataModel.get(selectionIndex);
        if (selected != null) {
            selectedId = selected.getId();
        }
    }


    public void selectCurrentRow() {
        if (selectedId != null) {
            Integer row = dataModel.getRowById(selectedId);
            if (row != null) {
                table.getSelectionModel().setSelectionInterval(row, row);
            } else {
                table.getSelectionModel().setSelectionInterval(0, 0);
            }
        } else {
            table.getSelectionModel().setSelectionInterval(0, 0);
        }
    }

    public void selectRow(Integer selectedId) {
        this.selectedId = selectedId;
        dataModel.load();
        selectCurrentRow();
    }

    public String getName() {
        return name;
    }

    public Integer getSelectedId() {
        return selectedId;
    }

    @Override
    public void rowInserted(Integer insertedId) {
        selectRow(insertedId);
    }

}
